
import './ElectronicFence.scss'
import { v4 } from 'uuid'
import * as mars3d from "mars3d"
import { useRequest } from 'alova/client'
import { useEventEmitter, useMount } from 'ahooks'
import { useState, useRef } from 'react'
import { Tree, Button, Result, App, Popconfirm } from 'antd'

import { PlusOutlined } from '@ant-design/icons';
import { Http } from '../../Utils/Api'
import { Decrypt } from '../../Utils/IndexedDB'
import { InitMars3dMap } from '../../Utils/Mars3dConfig'
import { modelStore } from '../../Config/zustand'


const labelConfig = {
    color: '#262626',
    font_size: 16,
    font_family: 'ShuHeiTi',
    font_weight: 'bold',
}


const ElectronicFence = () => {
    const { message, modal, notification } = App.useApp();
    const mapRef = useRef(null)
    const { updateModel } = modelStore()
    const FenceEvent = useEventEmitter()

    const { send } = useRequest(data => Http(data), { immediate: false })
    const [map, setMap] = useState()
    const [gra, setGra] = useState()
    const [treeData, setTreeData] = useState()
    const [Active, setActive] = useState()
    const [MapConfig, setMapConfig] = useState()
    const [ProList, setPorList] = useState([])
    const [ActiveArr, setActiveArr] = useState([])

    const [ModifyStatus, setModifyStatus] = useState('')

    const getOrgList = async () => {
        send({ method: 'GET', url: 'organization', params: { MenuType: '81981e9c-3689-4691-a776-f56c30b3ad25' } }).then(res => {
            setTreeData(res.data.list)
            setActive([res.data.list[0].value])
        })
        send({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: 'MapConfig/b1a4870a-c10c-4fba-a02b-e5c7af7f7a34' } }).then(async res => {
            setMapConfig(await Decrypt(res))
            setMapRender(await Decrypt(res))
        })
    }

    const setMapRender = (data) => {
        if (mapRef.current) {
            const { map, gra } = InitMars3dMap({ BOX: mapRef.current, DATA: data })
            setMap(map)
            setGra(gra)
        }
        else setTimeout(() => setMapRender(data), 500)
    }

    const onSelect = (e) => {
        if (e.length !== 0) {
            setActive(e)
            send({ method: 'get', url: 'fences', params: { organizationUuid: e[0], menuUuid: 'b15ae256-3e15-42b5-95ce-bf9ee20bf245', pageIndex: 1, pageSize: 100 } })
                .then(res => {
                    gra.clear()
                    res.data.list.map(item => {
                        const { uuid, color, width, tableName, coordinates } = item
                        const poly = new mars3d.graphic.PolylineEntity({
                            id: uuid,
                            positions: coordinates,
                            style: { closure: true, width, color, label: { text: tableName, ...labelConfig } },
                        })
                        gra.addGraphic(poly)
                    })
                    setPorList(res.data.list)
                })
        }
    }

    const onAddFence = () => {
        updateModel({ type: 'AddFormData', width: 640, title: '新增围栏', data: { type: 'AddFence', AddEvnet: FenceEvent, Initial: { color: '#13a8a8', width: 4 } } })
    }
    const onAddCallBack = async (data) => {
        const { uuid, color, width, tableName, onCallBack } = data
        if (onCallBack === 'onModify') {
            const obj = { uuid, color, width, tableName, coordinates: ActiveArr, organizationUuid: Active[0] }
            send({ method: 'PUT', url: 'fences', params: obj }).then(res => {
                notification.success({ message: '修改成功', key: 'fence' })
                onSelect(Active)
                setActiveArr([])
                FenceEvent.emit({ type: 'closeForm' })
            })
        } else {
            const id = v4()
            FenceEvent.emit({ type: 'closeForm' })
            message.loading({ duration: 0, content: '绘制已开启...', key: 'fence' })
            // gra.isAutoEditing = true
            gra.startDraw({
                id: uuid ? uuid : id,
                name: tableName,
                type: "polyline",
                style: { color, width, closure: true, label: { text: tableName, ...labelConfig } }
            }).then(res => {
                const obj = { uuid: uuid || id, color, width, tableName, coordinates: res.coordinates, organizationUuid: Active[0] }
                send({ method: 'POST', url: 'fences', params: obj }).then(res => {
                    message.success({ content: '绘制完成!', key: 'fence' })
                    onSelect(Active)
                })
            })
        }
    }

    const onSetPerson = (item) => {
        console.log('人员配置', item)

        console.log('OptionsModel', 'B02')

        const data = {
            transferType: 'table',
            searchArr: [
                { dataIndex: 'tableName', title: '全名称', width: 160 },
                { dataIndex: 'mobile', title: '手机号码', width: 160 },
                { dataIndex: 'organizationName', title: '所属公司', width: 160 },
            ],
            orgJoin: true,
            orgStatus: false,
            orgKeyValue: false,

            leftMethod: 'get',
            leftUrl: 'fences/GetAvailablePersonByFence',
            leftUuid: true,
            leftMapping: 'FenceUuid',

            rightMethod: 'get',
            rightUrl: 'fences/GetFenceByPerson',
            rightUuid: true,
            rightMapping: 'FenceUuid',

            saveMethod: 'post',
            saveUrl: 'fences/BatchAddPersonByFence',
            saveParams: '',
            saveSelect: 'personUuid',
            saveUuid: true,
            saveMapping: 'fenceUuid',
        }


        updateModel({
            type: 'OptionsModel',
            width: 1200,
            title: '添加人员',
            data: {
                row: { row: { data: item } },
                config: { type: 'B07', ...data },

            }
        })


        // { formType: 'TempTitle', label: '保存数据接口', name: 'transferApi3' },
        // { span: 24, formType: 'RADIO', name: 'saveMethod', label: '保存接口-请求方式', rules: true, valueEnum: MappingData.System__Method },
        // { span: 24, formType: 'INPUT', name: 'saveUrl', label: '保存接口-接口地址', rules: true },
        // { span: 24, formType: 'INPUT', name: 'saveParams', label: '保存接口-额外参数' },
        // { span: 24, formType: 'INPUT', name: 'saveSelect', label: '已选接口-选中键名' },
        // { span: 24, formType: 'RADIO', name: 'saveUuid', label: '已选接口-当前行Uuid', rules: true, valueEnum: MappingData.IsEnabledBool },
        // { span: 24, formType: 'INPUT', name: 'saveMapping', label: '已选接口-映射键名', jugdeField: 'saveUuid', jugdeValue: [true] },



    }
    const onModifyStyle = (item) => {
        updateModel({ type: 'AddFormData', width: 640, title: '修改样式', data: { type: 'AddFence', AddEvnet: FenceEvent, Initial: item, onCallBack: 'onModify' } })
        setActiveArr(item.coordinates)
    }
    const onModifyPosition = (item) => {
        setModifyStatus(item.uuid)
        gra.startEditing(gra.getGraphicById(item.uuid))
    }
    const onSavePosition = (item) => {
        const { graphics } = gra.stopEditing()
        const { coordinates } = graphics.find(v => v.id === item.uuid)
        const obj = { ...item, coordinates }
        send({ method: 'PUT', url: 'fences', params: obj }).then(res => {
            notification.success({ message: '修改成功', key: 'fence' })
            onSelect(Active)
        })
    }

    const onPositioning = (item) => {
        map.flyToGraphic(gra.getGraphicById(item.uuid))
    }
    const onDeleteFence = (item) => {
        send({ method: 'delete', url: 'fences', params: { Uuid: item.uuid } }).then(res => {
            notification.success({ message: '删除成功', key: 'fence' })
            onSelect(Active)
        })
    }

    const CallBackFunc = (e) => {
        const { type, data } = e
        // console.log('ElementEventBack', e)
        const MapReturn = new Map([
            ['onFormBack', () => onAddCallBack(data)],
        ])
        const func = MapReturn.get(type)
        return func && func()
    }
    FenceEvent.useSubscription(CallBackFunc)
    useMount(getOrgList)

    return (
        <div className='ElectronicFence'>
            <div className='OrgList'>
                {treeData &&
                    <Tree
                        defaultExpandAll
                        selectedKeys={Active}
                        fieldNames={{ key: 'value', title: 'label' }}
                        treeData={treeData}
                        onSelect={onSelect}
                    />
                }
            </div>
            <div className='MapInfo'>
                {MapConfig &&
                    <div className='MapBox'>
                        <div className='Map' ref={mapRef} />
                        {Active && Active[0] !== '40491731-928e-4b02-aa30-f45f4a3a563e' &&
                            <div className='MapList'>
                                <div className='List'>
                                    {ProList.length === 0 ?
                                        <Result status="404" title="暂无信息,请添加" /> :
                                        <div className='ListBox'>
                                            {ProList.map(item => {
                                                return (
                                                    <div key={item.uuid} className='List__item'>
                                                        <div>{item.tableName}</div>
                                                        <div>
                                                            <Button type='link' onClick={() => onSetPerson(item)}>人员配置</Button>
                                                            <Button type='link' onClick={() => onModifyStyle(item)}>修改样式</Button>
                                                            {ModifyStatus === item.uuid ?
                                                                <Button type='link' onClick={() => onSavePosition(item)}>保存位置</Button> :
                                                                <Button type='link' onClick={() => onModifyPosition(item)}>修改位置</Button>
                                                            }
                                                            <Button type='link' onClick={() => onPositioning(item)}>围栏定位</Button>
                                                            <Popconfirm
                                                                title="删除提醒!"
                                                                description="确认删除该围栏吗?"
                                                                onConfirm={() => onDeleteFence(item)}
                                                                okText="删除"
                                                                cancelText="取消"
                                                            >
                                                                <Button type='link' danger>删除围栏</Button>
                                                            </Popconfirm>
                                                        </div>
                                                    </div>
                                                )
                                            })}
                                        </div>
                                    }
                                </div>
                                <Button type='primary' icon={<PlusOutlined />} onClick={onAddFence}>新增电子围栏</Button>
                            </div>
                        }
                    </div>
                }
            </div>
        </div>
    );
};

export default ElectronicFence;